package org.example.ruangong.controller;

import org.example.ruangong.model.Result;
import org.example.ruangong.model.User;
import org.example.ruangong.service.EmailService;
import org.example.ruangong.service.UserService;
import org.example.ruangong.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.time.Duration;
import java.util.Map;
import java.util.Objects;

@Controller
@RequestMapping("/User")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private JwtUtil jwtUtil;
    @Autowired
    private EmailService emailService;
    @Autowired
    private RedisTemplate<String,Object> redisTemplate;


    // 注册用户
    @PostMapping("/addUser")
    @ResponseBody
    public Result addUser(@RequestBody User user) {
        // 检查必填参数
        if (user.getUname() == null || user.getUname().isEmpty() ||
                user.getEmail() == null || user.getEmail().isEmpty() ||
                user.getPassword() == null || user.getPassword().isEmpty()) {
            return Result.fail(400, "前端所传参数为空",null);
        }

        // 检查密码长度
        if (user.getPassword().length() < 6) {
            return Result.fail(400, "密码最少六位",null) ;
        }

        // 尝试添加用户
        boolean success = userService.addUser(user);
        if (success) {
            // 生成token
            String token = jwtUtil.generateToken(user.getEmail(), user.getUid());
            return Result.succ(200, "请求成功", token);
        } else {
            return Result.fail(501, "该邮箱注册过", null);
        }
    }

    // 注销用户
    @DeleteMapping("/delUserByID/{id}")
    @ResponseBody
    public Result deleteUser(@PathVariable("id") int id,
                                          @RequestHeader(value = "Authorization", required = false) String token) {
        // 检查token
        if (token == null || token.isEmpty()) {
            return Result.fail(401, "token的id与该账号id不同", null);
        }

        // 验证token并检查用户ID
        try {
            Integer uidFromToken = jwtUtil.getUidFromToken(token);
            if (uidFromToken == null || uidFromToken != id) {
                return Result.fail(401, "token的id与该账号id不同", null);
            }
        } catch (Exception e) {
            return Result.fail(401, "token的id与该账号id不同", null);
        }

        // 删除用户
        boolean success = userService.deleteUser(id);
        if (success) {
            return Result.succ(200, "请求成功", null);
        } else {
            return Result.fail(10003, "前端所查询的数据不存在", null);
        }
    }

    // 获取验证码
    @GetMapping("/getCode/{email}")
    @ResponseBody
    public Result getCode(@PathVariable("email") String email) {
        // 检查参数
        if (email == null || email.isEmpty()) {
            return Result.fail(400, "前端所传参数为空", null);
        }

        // 生成验证码
        String code = emailService.generateCode(6);

        // 发送邮件
        String emailSent = emailService.sendSimpleMessage(email,"您的邮箱验证码是：",code);

        if (emailSent.equals("邮件发送成功")) {
            // 保存验证码
            redisTemplate.opsForValue().set(email,code, Duration.ofMinutes(1L));
            return Result.succ(200, "请求成功", code);
        } else {
            return Result.fail(10003, "发送电子邮件失败", null);
        }
    }

    // 核对验证码去注册
    @PostMapping("/CheckcodeByadd")
    @ResponseBody
    public Result checkCodeByAdd(@RequestBody Map<String, String> requestData) {
        String email = requestData.get("email");
        String code = requestData.get("code");

        // 检查参数
        if (email == null || email.isEmpty() || code == null || code.isEmpty()) {
            return Result.fail(400, "前端所传参数为空", null);
        }

        // 检查邮箱是否已经注册
        if (userService.getUserByEmail(email) != null) {
            return Result.fail(501, "该邮箱注册过", null);
        }

        // 验证验证码

        if (Objects.equals(redisTemplate.opsForValue().get(email), code)) {
            redisTemplate.delete(email);
            return Result.succ(200, "请求成功", null);
        } else {
            return Result.fail(401, "验证码错误", null);
        }
    }

    // 通过验证码登录
    @PostMapping("/loginByCode")
    @ResponseBody
    public Result loginByCode(@RequestBody Map<String, String> requestData) {
        String email = requestData.get("email");
        String code = requestData.get("code");

        // 检查参数
        if (email == null || email.isEmpty() || code == null || code.isEmpty()) {
            return Result.fail(400, "前端所传参数为空", null);
        }

        // 检查邮箱是否已经注册
        if (userService.getUserByEmail(email) == null) {
            return Result.fail(503, "该邮箱未注册", null);
        }

        // 验证验证码

        if (Objects.equals(redisTemplate.opsForValue().get(email), code)) {
            User user = userService.getUserByEmail(email);
            redisTemplate.delete(email);
            String token = jwtUtil.generateToken(user.getEmail(), user.getUid());
            return Result.succ(200, "请求成功", token);
        } else {
            return Result.fail(401, "邮件未成功发送", null);
        }
    }

    // 通过密码登录
    @PostMapping("/logon")
    @ResponseBody
    public Result logon(@RequestBody Map<String, String> requestData) {
        String email = requestData.get("email");
        String password = requestData.get("password");

        // 检查参数
        if (email == null || email.isEmpty() || password == null || password.isEmpty()) {
            return Result.fail(400, "前端所传参数为空", null);
        }

        // 检查邮箱是否已经注册
        if (userService.getUserByEmail(email) == null) {
            return Result.fail(503, null, "该邮箱未注册");
        }

        // 验证密码
        boolean isValid = userService.verifyPassword(email, password);
        if (isValid) {
            User user = userService.getUserByEmail(email);
            String token = jwtUtil.generateToken(user.getEmail(), user.getUid());
            return Result.succ(200, "请求成功", token);
        } else {
            return Result.fail(502, "密码错误", null);
        }
    }

    // 修改密码
    @PutMapping("/UpdatePassword")
    @ResponseBody
    public Result updatePassword(@RequestBody Map<String, String> requestData) {
        String email = requestData.get("email");
        String password = requestData.get("password");
        String newPassword = requestData.get("newpassword");

        // 检查参数
        if (email == null || email.isEmpty() ||
                password == null || password.isEmpty() ||
                newPassword == null || newPassword.isEmpty()) {
            return Result.fail(400, "前端所传参数为空", null);
        }

        // 检查邮箱是否已经注册
        if (userService.getUserByEmail(email) == null) {
            return Result.fail(503, "该邮箱未注册", null);
        }

        // 更新密码
        boolean isUpdated = userService.updatePassword(email, password, newPassword);
        if (isUpdated) {
            return Result.succ(200, "请求成功", null);
        } else {
            return Result.fail(504, "密码错误", null);
        }
    }
}
